package client.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import client.AuctionClient;
import client.io.ConsoleOutputManager;

public class SocketListener implements Runnable{
	public static final int bufferSize = 1024*100; //100kb

	private AuctionClient manager;
	private DatagramSocket socket;
	private boolean workingFlag;

	public SocketListener(AuctionClient auctionClient, DatagramSocket listeningSocket) {
		this.manager = auctionClient;
		this.socket = listeningSocket;
		workingFlag = false;
	}

	
	public void run() {
		workingFlag = true;
		while( workingFlag ){
			try {
				byte[] buffer = new byte[bufferSize];
				DatagramPacket packet = new DatagramPacket(buffer, bufferSize);
				socket.receive(packet);
				String response = ""+new String(buffer, 0, packet.getLength());
				
				if(response.equals("!logout")){
					manager.destroyConnection();
				}
				else
					ConsoleOutputManager.addNotify(response);
				
			} catch (SocketException e){
				ConsoleOutputManager.addNotify("Listening socket closed."); 
			} catch (IOException e) {
				ConsoleOutputManager.addNotify("Listening socket can not open."); 
			}
		}
	}

	public void stopListening() {
		workingFlag = false;
		socket.close();
	}

}
